package com.ruoyi.api.service.impl;

import com.ruoyi.api.domain.*;
import com.ruoyi.api.repository.GuidRepository;
import com.ruoyi.api.repository.UserGuidRepository;
import com.ruoyi.api.service.*;
import com.ruoyi.api.vo.GuidDayVo;
import com.ruoyi.api.vo.GuidVo;
import com.ruoyi.api.vo.ScenicVo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GuidServiceImpl implements GuidService {

    @Autowired
    private GuidRepository guidRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserGuidRepository userGuidRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private GuidDayService guidDayService;
    @Autowired
    private GuidDayScenicService guidDayScenicService;
    @Autowired
    private ScenicService scenic;
    @Autowired
    private ISysUserService sysUserService;
    @Override
    public Page<GuidEntity> selectPage(GuidEntity loginBody, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);

        // 创建 Query 对象
        Query query = new Query();
        if (loginBody.getHot() != null) {
            query.addCriteria(Criteria.where("hot").is(loginBody.getHot()));
        }
        if(StringUtils.isNotEmpty(loginBody.getAddress())){
            // 使用 regex 进行模糊匹配，"i" 标志表示不区分大小写
            query.addCriteria(Criteria.where("address").regex(loginBody.getAddress(), "i"));
        }
        if(StringUtils.isNotEmpty(loginBody.getRegion())){
            // 使用 regex 进行模糊匹配，"i" 标志表示不区分大小写
            query.addCriteria(Criteria.where("address").is(loginBody.getRegion()));
        }
//        if(StringUtils.isNotEmpty(loginBody.getCategories())){
//            // 使用 regex 进行模糊匹配，"i" 标志表示不区分大小写
//            query.addCriteria(Criteria.where("categories").is(loginBody.getCategories()));
//        }
        long count = mongoTemplate.count(query, GuidEntity.class);
        List<GuidEntity> entities = mongoTemplate.find(query.with(pageable), GuidEntity.class);

        return new PageImpl<>(entities, pageable, count);
    }

    @Override
    public List<GuidEntity> selectAll() {
        return guidRepository.findAll();
    }

    @Override
    public List<UserGuidEntity> checkGuid(UserEntity user, String type) {
        List<UserGuidEntity> guidEntities = userGuidRepository.findByEmailType(user.getId(),type);
        guidEntities.stream().iterator();
        return guidEntities;
    }

    @Override
    public GuidEntity selectById(Object id) {
       return guidRepository.findById(new ObjectId(String.valueOf(id))).get();
    }

    @Override
    public GuidEntity insertUser(GuidEntity user) {
        return guidRepository.save(user);
    }

    @Override
    public GuidEntity getById(String id) {
        return guidRepository.findById(new ObjectId(String.valueOf(id))).get();
    }

    @Override
    public void updateCate(String id, String[] split) {
        // 创建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("guidId").is(id));  // 根据实际需要设置查询条件
        //删除该计划类型
        mongoTemplate.remove(query,GuidCateEntity.class);
        //新增该计划类型
        List<GuidCateEntity> list = new ArrayList<>();
        for ( String S:
        split) {
            GuidCateEntity guidCateEntity = new GuidCateEntity();
            guidCateEntity.setGuidId(id);
            guidCateEntity.setCategory(S);
            list.add(guidCateEntity);
        }
        mongoTemplate.insertAll(list);
    }

    @Override
    public List<GuidEntity> setCate(List<GuidEntity> content) {
        for (GuidEntity guidEntity:
                content) {
            // 创建查询条件
            Query query = new Query();
            query.addCriteria(Criteria.where("guidId").is(guidEntity.getId()));
            List<GuidCateEntity> cateEntityList = mongoTemplate.find(query,GuidCateEntity.class);
            if(null!=cateEntityList){
                // 从查询结果中提取 'category' 字段的值
                List<String> categories = cateEntityList.stream()
                        .map(GuidCateEntity::getCategory) // 替换为实际的 getter 方法
                        .collect(Collectors.toList());
                guidEntity.setCategories(String.join(",",categories));
            }
        }
        return content;
    }

    @Override
    public List<String> selectGuidByCate(List<String> check) {

        // 创建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("category").in(check));
        List<GuidCateEntity> cateEntityList = mongoTemplate.find(query,GuidCateEntity.class);
        if(null!=cateEntityList){
            // 从查询结果中提取 'category' 字段的值
            List<String> categories = cateEntityList.stream()
                    .map(GuidCateEntity::getGuidId) // 替换为实际的 getter 方法
                    .collect(Collectors.toList());
            return categories;
        }
        return null;
    }

    @Override
    public GuidVo setPlans(GuidEntity guidEntity) {
        //获取天数计划
        List<GuidDayVo> list = new ArrayList<>();
        List<GuidDayEntity> guidDayEntities = guidDayService.getInfoByGuidId(guidEntity.getId());
        int i = 0;
        for (GuidDayEntity guidDayEntity:
        guidDayEntities) {
            i = i + 1;

            GuidDayVo vo = new GuidDayVo();
            vo.setName(i+"");
            vo.setTitle(guidDayEntity.getName());
            vo.setDate(guidDayEntity.getDate());
            List<GuidDayScenicEntity> guidDayScenicEntityList = guidDayScenicService.getScenicIdsByGuidDayId(guidDayEntity.getId());

            if(null!=guidDayScenicEntityList){
                List<ScenicVo> scenicEntities = new ArrayList<>();

                for (GuidDayScenicEntity guidDayScenicEntity:
                        guidDayScenicEntityList) {
                    ScenicVo scenicVo = new ScenicVo();

                    ScenicEntity scenicEntityList = scenic.getInfoById(ScenicEntity.class,guidDayScenicEntity.getScenicId(),mongoTemplate);
                    BeanUtils.copyProperties(scenicEntityList,scenicVo);
                    if(null!=guidDayScenicEntity.getStartTime() && null!=guidDayScenicEntity.getEndTime()){
                        scenicVo.setStartTime(guidDayScenicEntity.getStartTime());
                        scenicVo.setEndTime(guidDayScenicEntity.getEndTime());
                    }
                    if(null!=guidDayScenicEntity.getTime()){
                        scenicVo.setTime(guidDayScenicEntity.getTime());
                    }
                    if(null!=guidDayScenicEntity.getRemark()){
                        scenicVo.setRemark(guidDayScenicEntity.getRemark());
                    }
                    if(null!=guidDayScenicEntity.getKm()){
                        scenicVo.setKm(guidDayScenicEntity.getKm());
                    }
                    if(null!=guidDayScenicEntity.getMiu()){
                        scenicVo.setMiu(guidDayScenicEntity.getMiu());
                    }
                    scenicEntities.add(scenicVo);
                }
                vo.setContent(scenicEntities);
            }

            list.add(vo);
        }
        GuidVo guidVo = new GuidVo();
        BeanUtils.copyProperties(guidEntity,guidVo);
        guidVo.setPlans(list);
        UserEntity userEntity = userService.selectUserByEmail(guidVo.getAttribute());
        if(null!=userEntity){
            guidVo.setAvatar(null != userEntity.getAvatar()?userEntity.getAvatar():null);
        }else{
            SysUser SysUser = sysUserService.selectUserByUserName(guidVo.getAttribute());
            guidVo.setAvatar(null);
        }

        return guidVo;
    }

}
